package com.line.runner;

import com.line.config.cons.RedisCons;
import com.line.dao.AuthAppRepository;
import com.line.dao.AuthAppResRepository;
import com.line.dao.AuthResRepository;
import com.line.model.entity.AuthAppEntity;
import com.line.model.entity.AuthAppResEntity;
import com.line.model.entity.AuthResEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.core.annotation.Order;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.*;

@Component
@Order(value = 1)
public class InitRunner implements CommandLineRunner {

	@Autowired
	private RedisTemplate<String, Object> redisTemplate;

	@Autowired
	private AuthAppRepository appRepository;

	@Autowired
	private AuthAppResRepository appResRepository;

	@Autowired
	private AuthResRepository resRepository;

	@Override
	public void run(String... args) throws Exception {
		// 初始化appid帐号
		initApps();
		// 初始化app与资源绑定
		initAppRes();
	}

	private void initApps() {
		List<AuthAppEntity> appList = appRepository.findAll();
		for (AuthAppEntity entity : appList) {
			String redisKey = RedisCons.AUTH_APPID + entity.getAppid();
			redisTemplate.opsForValue().set(redisKey, entity);
		}
	}

	private void initAppRes() {
		Map<Long, List<Long>> appResMap = new HashMap<>();
		List<AuthAppResEntity> appResList = appResRepository.findAll();
		for (AuthAppResEntity entity : appResList) {
			List<Long> list = appResMap.get(entity.getResId());
			if (list == null) {
				list = new ArrayList<>();
			}
			list.add(entity.getAppId());
			appResMap.put(entity.getResId(), list);
		}

		// 2.查询客户端表
		Map<Long, AuthAppEntity> appMap = new HashMap<>();
		List<AuthAppEntity> appList = appRepository.findAll();
		for (AuthAppEntity entity : appList) {
			appMap.put(entity.getId(), entity);
		}

		// 3.查询资源列表
		List<AuthResEntity> resList = resRepository.findAll();
		for (AuthResEntity entity : resList) {

			List<Long> list = appResMap.get(entity.getId());
			if (list == null) {
				continue;
			}
			Set<String> listClient = new HashSet<>();
			for (Long clientId : list) {
				if (appMap.containsKey(clientId)) {
					listClient.add(appMap.get(clientId).getAppid());
				}
			}

			String path = entity.getPath().replaceAll("/", ":");
			String redisKey = RedisCons.AUTH_RES + entity.getPrefix() + path;
			redisTemplate.opsForValue().set(redisKey, listClient);
		}
	}

}
